package cn.xyinping.org.service.impl;

import cn.xyinping.basic.service.impl.BasicServiceImpl;
import cn.xyinping.basic.util.PageList;
import cn.xyinping.org.domain.Department;
import cn.xyinping.org.mapper.DepartmentMapper;
import cn.xyinping.org.query.DepartmentQuery;
import cn.xyinping.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 27266
 * @desrciption
 * @date 2021/10/17
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BasicServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.add(department); // 返回自增长的id
        /*
        * 1)判断是否是顶级部门  dirPath = 自己的id
          2)不是顶级部门，dirPath = 上级部门的dirPath+/+自己的id
        * */
       /* if(department.getParent()==null){ // 判断是否是顶级部门
            department.setDirPath("/"+ department.getId()); //  dirPath = 自己的id
        }else {
            Department parentDept = departmentMapper.loadById(department.getParent().getId()); // 获取上级部门的Id
            String dirPath = parentDept.getDirPath(); // 获取上级部门的dirPath
            department.setDirPath(dirPath+"/"+department.getId()); // 拼接获取完整的dirPath
        }*/
        // 更新 应为调用了update所以不用在新增中写了
        update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        /*
        * 如果新增那样写当dirPath改为空是就会报错，所以还要判断一下
        * */
        if(department.getParent()==null || department.getParent().getId()==null   ){ // 判断是否是顶级部门
            department.setDirPath("/"+ department.getId()); //  dirPath = 自己的id
        }else {
            Department parentDept = departmentMapper.loadById(department.getParent().getId()); // 获取上级部门的Id
            String dirPath = parentDept.getDirPath(); // 获取上级部门的dirPath
            department.setDirPath(dirPath+"/"+department.getId()); // 拼接获取完整的dirPath
        }
        departmentMapper.update(department);
    }
    @Override
    public List<Department> queryTree() {
        return departmentMapper.loadTree();
    }
}
